<template>
  <view class="dynamic-details-card">
    <!-- 配置驱动的动态展示 -->
    <view v-for="section in sections" :key="section.key" class="info-section">
      <view class="section-title">{{ section.title }}</view>

      <view v-for="field in section.fields" :key="field.key" class="info-item">
        <text class="label">{{ field.label }}</text>

        <!-- 只读字段 -->
        <text v-if="field.type === 'readonly'" class="value readonly-value">
          {{ getFieldDisplayValue(field.key) }}
        </text>

        <!-- 文本类型字段 -->
        <text
          v-else-if="
            field.type === 'input' ||
            field.type === 'textarea' ||
            field.type === 'text'
          "
          class="value"
        >
          {{ getFieldDisplayValue(field.key) }}
        </text>

        <!-- 日期时间类型字段 -->
        <text
          v-else-if="
            field.type === 'datetime' ||
            field.type === 'date' ||
            field.type === 'native-date'
          "
          class="value"
        >
          {{ formatDateTime(getFieldRawValue(field.key)) }}
        </text>

        <!-- 选择器类型字段（含部门选择器） -->
        <text
          v-else-if="
            field.type === 'picker' ||
            field.type === 'select' ||
            field.type === 'department-picker'
          "
          class="value"
        >
          {{ getPickerDisplayValue(field.key) }}
        </text>

        <!-- 图片上传类型字段 -->
        <view
          v-else-if="field.type === 'image-upload' || field.type === 'image'"
          class="value"
        >
          <view v-if="getImageFileId(field.key)" class="image-preview">
            <image
              :src="getImageUrl(getImageFileId(field.key))"
              class="detail-image"
              :class="getImageClass(field)"
              mode="aspectFit"
              @error="handleImageError"
              @tap="handleImagePreview(field.key, field.label)"
            />
          </view>
          <text v-else class="empty-value">暂无图片</text>
        </view>

        <!-- 文件上传类型字段 -->
        <view v-else-if="field.type === 'file-upload'" class="value">
          <view v-if="getFileInfo(field.key)" class="file-info">
            <uni-icons type="paperclip" size="16" color="#666"></uni-icons>
            <text class="file-name">{{ getFileName(field.key) }}</text>
          </view>
          <text v-else class="empty-value"></text>
        </view>

        <!-- 状态标签字段 -->
        <view v-else-if="isStatusField(field.key)" class="value">
          <view class="status-tag" :class="getStatusClass(field.key)">
            {{ getFieldDisplayValue(field.key) }}
          </view>
        </view>

        <!-- 自定义字段插槽 -->
        <slot
          v-else
          :name="`field-${field.key}`"
          :field="field"
          :value="getFieldRawValue(field.key)"
          :displayValue="getFieldDisplayValue(field.key)"
        >
          <!-- 默认渲染 -->
          <text class="value">
            {{ getFieldDisplayValue(field.key) }}
          </text>
        </slot>
      </view>
    </view>

    <!-- 自定义分组插槽 -->
    <slot
      name="custom-sections"
      :data="data"
      :field-mapping="fieldMapping"
    ></slot>
  </view>
</template>

<script setup lang="ts">
// 通用字段配置接口
interface FieldConfig {
  key: string;
  label: string;
  type:
    | "input"
    | "textarea"
    | "picker"
    | "datetime"
    | "image-upload"
    | "image"
    | "file-upload"
    | "readonly"
    | "text"
    | "date"
    | "native-date"
    | "select"
    | "department-picker"
    | "autocomplete";
  required?: boolean;
  fileConfig?: any; // 使用 any 类型以兼容不同模块的 fileConfig 定义
  formatter?: (value: any) => string;
  visible?: (data: any) => boolean;
}

// 通用表单分组接口
interface FormSection {
  key: string;
  title: string;
  icon?: string;
  fields: FieldConfig[];
}

// 组件属性
interface Props {
  sections: FormSection[];
  data: any;
  fieldMapping: Record<string, string>;
  getImageUrl?: (fileId: string | null) => string;
}

const props = defineProps<Props>();

// 事件定义
const emit = defineEmits<{
  (e: "preview-image", fileId: string | null, label: string): void;
}>();

// 获取字段原始值
const getFieldRawValue = (fieldKey: string): any => {
  const apiPath = props.fieldMapping[fieldKey];
  if (!apiPath) return null;

  // 处理嵌套属性路径
  const pathParts = apiPath.split(".");
  let value = props.data;

  for (const part of pathParts) {
    if (value && typeof value === "object" && part in value) {
      value = (value as any)[part];
    } else {
      return null;
    }
  }

  return value;
};

// 获取字段显示值
const getFieldDisplayValue = (fieldKey: string): string => {
  const value = getFieldRawValue(fieldKey);

  // 查找对应的字段配置
  for (const section of props.sections) {
    const field = section.fields.find((f) => f.key === fieldKey);
    if (field && field.formatter) {
      return field.formatter(value);
    }
  }

  return value || "";
};

// 获取选择器显示值
const getPickerDisplayValue = (fieldKey: string): string => {
  // 访客模块
  if (fieldKey === "visitorReason") {
    return props.data.VisitorReason?.ReasonName || "";
  }
  if (fieldKey === "group") {
    return props.data.Group?.GroupName || "";
  }

  // 调岗调薪模块：根据关联对象优先显示名称，避免ID展示
  if (fieldKey === "originalGroupId" || fieldKey === "originalGroup") {
    return (
      props.data.OriginalGroup?.GroupName ||
      props.data.OriginalGroupName ||
      getFieldDisplayValue(fieldKey)
    );
  }
  if (fieldKey === "newGroupId" || fieldKey === "newGroup") {
    return (
      props.data.NewGroup?.GroupName ||
      props.data.NewGroupName ||
      getFieldDisplayValue(fieldKey)
    );
  }
  if (fieldKey === "originalPositionId") {
    return props.data.OriginalPosition?.Name || getFieldDisplayValue(fieldKey);
  }
  if (fieldKey === "newJobPositionId") {
    return props.data.NewPosition?.Name || getFieldDisplayValue(fieldKey);
  }

  return getFieldDisplayValue(fieldKey);
};

// 获取图片文件ID
const getImageFileId = (fieldKey: string): string | null => {
  // 访客系统的图片字段映射
  if (fieldKey === "idCardFrontPhoto") {
    return props.data.IdCardFrontPhotoId || null;
  } else if (fieldKey === "idCardBackPhoto") {
    return props.data.IdCardBackPhotoId || null;
  }

  // HR档案补录系统的图片字段映射
  if (fieldKey === "PhotoId") {
    return props.data.PhotoId || null;
  } else if (fieldKey === "IdCardFrontPhotoId") {
    return props.data.IdCardFrontPhotoId || null;
  } else if (fieldKey === "IdCardBackPhotoId") {
    return props.data.IdCardBackPhotoId || null;
  } else if (fieldKey === "VeteranCertificateId") {
    return props.data.VeteranCertificateId || null;
  }

  return getFieldRawValue(fieldKey);
};

// 获取图片URL
const getImageUrl = (fileId: string | null): string => {
  if (!fileId) return "";
  // 如果传入了自定义的getImageUrl函数，使用它
  if (props.getImageUrl) {
    return props.getImageUrl(fileId);
  }
  // 否则使用默认实现
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 获取图片样式类
const getImageClass = (field: FieldConfig): string => {
  // 兼容不同模块的 fileConfig 结构
  if (field.fileConfig && typeof field.fileConfig === "object") {
    if (field.fileConfig.isIdCard) {
      return "id-card-photo";
    }
  }
  return "general-photo";
};

// 获取文件信息
const getFileInfo = (fieldKey: string): any => {
  const fileData = getFieldRawValue(fieldKey);

  // 如果是文件数组，返回第一个文件用于显示
  if (Array.isArray(fileData) && fileData.length > 0) {
    return fileData[0];
  }

  // 如果是单个文件对象
  if (fileData && typeof fileData === "object") {
    return fileData;
  }

  return null;
};

// 获取文件名
const getFileName = (fieldKey: string): string => {
  const fileInfo = getFileInfo(fieldKey);
  if (!fileInfo) return "暂无文件";

  const fileData = getFieldRawValue(fieldKey);

  // 如果是文件数组，显示文件数量
  if (Array.isArray(fileData) && fileData.length > 1) {
    return `${fileInfo.name || fileInfo.fileName || "文件"} 等${
      fileData.length
    }个文件`;
  }

  return fileInfo?.name || fileInfo?.fileName || "未知文件";
};

// 格式化日期时间 - 使用统一的格式化工具
const formatDateTime = (dateStr: string | Date | null) => {
  if (!dateStr) return "";

  let date: Date;

  // 如果已经是Date对象，直接使用
  if (dateStr instanceof Date) {
    date = dateStr;
  }
  // 如果是数字类型的时间戳，直接使用
  else if (typeof dateStr === "number") {
    date = new Date(dateStr);
  }
  // 如果是字符串，需要处理iOS兼容性
  else {
    const timeStr = dateStr.toString();

    // 处理常见的时间格式，转换为iOS兼容格式
    let isoString = timeStr;

    // 如果是 "yyyy-MM-dd HH:mm:ss" 格式，转换为 "yyyy/MM/dd HH:mm:ss"
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(timeStr)) {
      isoString = timeStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3");
    }
    // 如果是 "yyyy-MM-dd" 格式，转换为 "yyyy/MM/dd"
    else if (/^\d{4}-\d{2}-\d{2}$/.test(timeStr)) {
      isoString = timeStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3");
    }
    // 如果是完整的GMT格式（如 "Tue Sep 16 2025 10:19:08 GMT+0800 (CST)"），直接使用
    // 这种格式通常是服务端返回的完整时间字符串，浏览器可以正确解析
    // 如果是ISO 8601格式（yyyy-MM-ddTHH:mm:ss），iOS原生支持，直接使用
    // 其他格式也直接尝试使用

    date = new Date(isoString);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return "";
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 处理图片预览
const handleImagePreview = (fieldKey: string, label: string) => {
  const fileId = getImageFileId(fieldKey);
  emit("preview-image", fileId, label);
};

// 处理图片加载错误
const handleImageError = (e: any) => {
  console.warn("图片加载失败:", e);
};

// 判断是否为状态字段
const isStatusField = (fieldKey: string): boolean => {
  const statusFields = ["billStatus", "workflowStatus"];
  return statusFields.includes(fieldKey);
};

// 获取状态样式类
const getStatusClass = (fieldKey: string): string => {
  const value = getFieldDisplayValue(fieldKey);

  if (fieldKey === "billStatus") {
    switch (value) {
      case "草稿":
        return "status-draft";
      case "已提交":
        return "status-submitted";
      case "已审批":
        return "status-approved";
      case "已拒绝":
        return "status-rejected";
      default:
        return "status-default";
    }
  }

  if (fieldKey === "workflowStatus") {
    switch (value) {
      case "待提交":
        return "status-pending";
      case "提交中":
        return "status-processing";
      case "已完成":
        return "status-completed";
      case "已取消":
        return "status-cancelled";
      default:
        return "status-default";
    }
  }

  return "status-default";
};
</script>

<style lang="scss" scoped>
.dynamic-details-card {
  .info-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 16px;
      position: relative;
      padding-left: 12px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
        border-radius: 2px;
      }
    }

    .info-item {
      display: flex;
      margin-bottom: 12px;
      align-items: baseline;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 80px;
        color: #666;
        font-size: 14px;
        flex-shrink: 0;
      }

      .value {
        flex: 1;
        color: #333;
        font-size: 14px;
        word-break: break-all;

        &.readonly-value {
          color: #333;
          font-style: normal;
        }
      }

      .empty-value {
        flex: 1;
        color: #999;
        font-size: 14px;
        font-style: italic;
      }
    }

    .image-preview {
      display: flex;
      align-items: center;
    }

    .file-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .file-name {
        color: #333;
        font-size: 14px;
      }
    }
  }
}

/* 图片样式 */
.detail-image {
  border-radius: 6px;
  border: 2px solid #e5e7eb;
  background-color: #ffffff;
  transition: all 0.3s ease;
  cursor: pointer;

  &:active {
    border-color: #7881de;
    box-shadow: 0 4px 8px rgba(120, 129, 222, 0.2);
    transform: scale(0.98);
  }

  &.id-card-photo {
    width: 120px;
    height: 76px;
  }

  &.general-photo {
    width: 100px;
    height: 100px;
  }
}

/* 状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 60px;

  &.status-draft {
    background-color: #f3f4f6;
    color: #6b7280;
    border: 1px solid #d1d5db;
  }

  &.status-submitted {
    background-color: #dbeafe;
    color: #1d4ed8;
    border: 1px solid #93c5fd;
  }

  &.status-approved {
    background-color: #dcfce7;
    color: #16a34a;
    border: 1px solid #86efac;
  }

  &.status-rejected {
    background-color: #fee2e2;
    color: #dc2626;
    border: 1px solid #fca5a5;
  }

  &.status-pending {
    background-color: #fef3c7;
    color: #d97706;
    border: 1px solid #fcd34d;
  }

  &.status-processing {
    background-color: #e0e7ff;
    color: #4338ca;
    border: 1px solid #a5b4fc;
  }

  &.status-completed {
    background-color: #d1fae5;
    color: #059669;
    border: 1px solid #6ee7b7;
  }

  &.status-cancelled {
    background-color: #f5f5f5;
    color: #737373;
    border: 1px solid #d4d4d4;
  }

  &.status-default {
    background-color: #f9fafb;
    color: #374151;
    border: 1px solid #e5e7eb;
  }
}
</style>
